package com.burgeon.backend.SHOP.service.Impl;

import com.burgeon.backend.SHOP.entity.*;
import com.burgeon.backend.SHOP.entity.presell.Presell;
import com.burgeon.backend.SHOP.mappers.*;
import com.burgeon.backend.SHOP.rest.*;
import com.burgeon.backend.SHOP.service.*;
import com.burgeon.backend.SHOP.service.ex.OrderExceptionApp;
import com.burgeon.backend.SHOP.service.util.AddressUtil;
import com.burgeon.backend.SHOP.service.util.MathUtil;
import com.burgeon.backend.SHOPBACKEND.entity.ShopKf;
import com.burgeon.backend.SHOPBACKEND.mappers.WeChatKfMapper;
import com.burgeon.backend.SHOPBACKEND.rest.QuerryMailFee;
import com.burgeon.backend.entity.Coupon;
import com.burgeon.backend.entity.Info;
import com.burgeon.backend.mappers.AccountMapper;
import com.burgeon.backend.service.QueueService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {
    private final static Log logger = LogFactory.getLog(OrderService.class);


    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private AddressService addressService;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private BasketMapper basketMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private PayWechatService payWechatService;
    @Autowired
    private MailService mailService;
    @Autowired
    private AppActivityService appActivityService;
    @Autowired
    private AppCouponMapper appCouponMapper;
    @Autowired
    private SeckillMapper seckillMapper;
    @Autowired
    private EmpNotificationMessageService empNotificationMessageService;
    @Autowired
    private WeChatKfMapper weChatKfMapper;
    @Autowired
    private QueueService queueService;

    @Override
    public PayData createOrderByBasketZT(String uid, String openid, String phoneZT, String nameZT, String dateZT, String cid, String phone, String token, String comment,String store,String distance, String emp, String discount, String isPlus) throws OrderExceptionApp {


        Info info = GetInfo(token);
        int self = new Random().nextInt(9000000) + 1000000;//提货码
        BigDecimal RECOUNT = new BigDecimal(0); //总实付金额

        String orderid = getOrderIdByUUId();
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String now = sdf.format(date);

        List<Basket> baskets = basketMapper.thisVipSelectedData(uid, token);

        // 遍历并计算总价：
        int totalPrice = 0;
        int totalIntegral = 0;

        int rp;
        int Coupond;
        ArrayList<Goods> disList = new ArrayList<Goods>();
        try {
            //判断优惠券是否可用 是 返回金额 否 返回异常

            //计算总 原价
            for (Basket basket : baskets) {
                Goods goods = goodsMapper.getGoods(basket.getGid());

                System.err.println(Long.parseLong(goods.getPrice()));
                System.err.println(Long.valueOf(basket.getNum()));

                //判断plus会员
                if (!"Y".equals(isPlus)) {
                    goods.setPlusPrice(null);
                }

                //计算会员价
                if ("Y".equals(goods.getIsVipPrice())) {
                    goods.setVipPrice(String.valueOf(MathUtil.multiply(new BigDecimal(goods.getOriginal()), new BigDecimal(discount), 0)));
                }


                goods.setPrice(minPrice(goods.getPrice(), goods.getVipPrice(), goods.getPlusPrice()));

                totalPrice += Long.parseLong(goods.getPrice()) * Long.valueOf(basket.getNum());
                totalIntegral += Long.valueOf(goods.getIntegral());
                //判断库存
                determineTheInventory(info, basket.getCode(), Integer.parseInt(basket.getNum()));

                if (null != goods.getActivityId() && !"0".equals(goods.getActivityId())) {
                    goods.setActivitieitem(appActivityService.getActvityById(goods.getActivityId()));

                    for (int i = 0; i < Integer.parseInt(basket.getNum()); i++) {
                        if (null == goods.getActivitieitem() || !"N".equals(goods.getActivitieitem().getIsUse())) {
                            disList.add(goods);
                        }
                    }

                }
                basket.setGoods(goods);
            }

            rp = goodsActivity(totalPrice, disList);

            //需要的积分不等于0 判断会员积分
            if (totalIntegral > 0) {
                GETUserByOpenid getUserByOpenid = new GETUserByOpenid(info.getUrl(), info.getAccount(), info.getPassword());
                int integral = Integer.parseInt(getUserByOpenid.getData(openid).getIntegral());
                if (totalIntegral > integral) {
                    throw new OrderExceptionApp("创建订单失败！积分不足！");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new OrderExceptionApp(e.getMessage());
        }
        Coupon coupon = calculateCoupon(info, cid, totalPrice);
        Coupond = Integer.parseInt(coupon.getMoney());
        //计算总成交价
        System.err.println(totalPrice);
        rp = ActualPayment(rp, 0, Coupond);
        System.err.println("rp = " + rp);
        //计算总折扣

        BigDecimal bigDecimal = CalculateDiscount(rp, totalPrice);

        // 创建订单Order对象
        Order order = new Order();
        // 向Order对象封装uid
        order.setUid(uid);
        // 根据aid查询地址数据：addressService.getByAid(aid)

        //零售单数据
        ArrayList<ArrayList> RETAIL = new ArrayList();
        /*RETAIL.put("Price",totalPrice);*/
        for (Basket basket : baskets) {
            //*********************************
            //零售单明细
            // for (int i = 0; i < Integer.parseInt(basket.getNum()); i++) {
            ArrayList list = new ArrayList();
            BigDecimal bigDecimal1 = CalculateUnit(Integer.parseInt(basket.getGoods().getPrice()) * Integer.parseInt(basket.getNum()), bigDecimal);
            RECOUNT = MathUtil.add(RECOUNT, bigDecimal1, 2);//加入总价
            list.add(basket.getCode());
            list.add(basket.getNum());
            list.add(bigDecimal1.toString());
            RETAIL.add(list);
            //  }
        }
        String orderType = "Z";
        //积分调整接口 积分大于0执行

        if (totalIntegral > 0) {
            CreateIntegral createIntegral = new CreateIntegral(info.getUrl(), info.getAccount(), info.getPassword());

            try {

                order.setIntegralCode(createIntegral.getData(phone, Long.toString(totalIntegral)));

            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.getMessage());
                order.setIntegralMessage(e.getMessage());
                throw new OrderExceptionApp("积分调整单错误" + e.getMessage());
            }
        }

        CreateYCRETAIL_ZT createYCRETAIL_ZT = new CreateYCRETAIL_ZT(info.getUrl(), info.getAccount(), info.getPassword());
        //FindStoreData findStoreData = new FindStoreData(info.getUrl(), info.getAccount(), info.getPassword());

        try {//orderType  Z:正常订单,S:秒杀订单,P:拼团订单,K:砍价订单,Y:预售订单,
            //计算距离
            String row = createYCRETAIL_ZT.getData(orderType, RETAIL, store, distance, phoneZT,
                    nameZT, RECOUNT.toString(), phone, orderid, coupon, self + "", dateZT, emp, comment);
            order.setRetailCode(row);
        } catch (Exception e) {
            logger.error(e.getMessage());
            order.setRetailMessage(e.getMessage());
            throw new OrderExceptionApp("零售单错误" + e.getMessage());
        }

        // 向Order对象封装receiver,phone,address
        order.setReceiver(nameZT);
        order.setPhone(phone);
        order.setAddress("会员自提:" + store);
        // 向Order对象封装state值为0
        order.setState("0");
        // 向Order对象封装orderTime为now
        //封装订单号
        order.setOrderId(orderid);
        order.setOrderTime(now);
        // 向Order对象封装total_price
        order.setTotalPrice(RECOUNT.toString().replace(".00", ""));
        order.setTotalIntegral(Long.toString(totalIntegral));
        // 向Order对象封装4项日志
        order.setCreatedUser(phone);
        order.setCreatedTime(now);
        order.setModifiedUser(phone);
        order.setModifiedTime(now);
        // 执行插入订单数据：insertOrder(order);
        order.setToken(token);
        order.setAccount(token);
        order.setMailFee("0");
        order.setSelf(self+"");
        insertOrder(order);
        // 遍历查询结果
        for (Basket basket : baskets) {
            // 创建OrderItem对象
            OrderItem item = new OrderItem();
            // 向OrderItem对象中封装商品相关的5个数据
            item.setGoodsId(basket.getGid());
            item.settName(basket.getType());
            item.setCode(basket.getCode());
            item.setGoodsTitle(basket.getGoods().getName());
            item.setGoodsImage(basket.getGoods().getImg());
            item.setGoodsPrice(CalculateUnit(Integer.parseInt(basket.getGoods().getPrice()), bigDecimal).toString());
            System.err.println(item.getGoodsPrice());
            item.setGoodsIntegral(basket.getGoods().getIntegral());
            item.setGoodsNum(basket.getNum());

            item.setOid(order.getId());
            // 向OrderItem对象中封装日志
            item.setCreatedUser(phone);
            item.setCreatedTime(now);
            item.setModifiedUser(phone);
            item.setModifiedTime(now);
            //执行插入订单商品数据：insertOrderItem(orderItem);
            insertOrderItem(item);
        }
        if (null != cid) {
            UseCoupon(cid, info);//核销优惠券
        }

        // 删除购物车对应数据
        StringBuffer title = new StringBuffer();
        for (Basket basket : baskets) {
            basketMapper.delData(basket.getId());
            title.append(basket.getGoods().getName()).append("*").append(basket.getNum()).append(";");
        }

        PayData data = new PayData();//test
      //  RECOUNT = MathUtil.add(RECOUNT, BigDecimal.valueOf(Integer.parseInt(mail.getPrice())), 0);//test
        if (RECOUNT.doubleValue() > 0) {
            try {
                String notify_url = "https://lfwd.cloudsmicro.com/shop/pay/result";
                data = payWechatService.createUnified(notify_url, openid, token, order.getOrderId(), RECOUNT.toString(), String.valueOf(title));
                //返回
                data.setOrderId(order.getId());
            } catch (Exception e) {
                e.printStackTrace();
            }
            data.setType("price");
        } else {
            data.setOrderId(order.getId());
            integralPay(info, order, data);
        }

        return data;
    }

//普通下单自提
    @Override
    public PayData CreateOrderZT(String uid, String openid, String phoneZT, String nameZT, String gid, String cid,
                                 String code, String store, String distance, String dateZT, String type, String phone,
                                 String token, String emp, String comment, String discount, String isPlus) throws OrderExceptionApp {

        Info info = GetInfo(token);
        Goods goods = goodsService.findGoodsById(gid, uid, discount, isPlus);
        int self = new Random().nextInt(9000000) + 1000000;//提货码
        //判断库存
        determineTheInventory(info, code, 1);

        System.err.println(goods.getIntegral());

        Date date = new Date();
        String orderid = getOrderIdByUUId(); //订单号


        //计算满减价格
        List<Goods> goodsList = new ArrayList<>();
        if (null != goods.getActivityId() && !"0".equals(goods.getActivityId())) {
            goods.setActivitieitem(appActivityService.getActvityById(goods.getActivityId()));
            if (null == goods.getActivitieitem() || !"N".equals(goods.getActivitieitem().getIsUse())) {
                goodsList.add(goods);
            }
        }

        int rp = goodsActivity(Integer.parseInt(goods.getPrice()), goodsList);

        //优惠券金额
        int Coupond;
        Coupon coupon = calculateCoupon(info, cid, Integer.parseInt(goods.getPrice()));
        try {
            //判断优惠券是否可用 是 返回金额 否 返回异常
            //Coupond = Integer.parseInt(calculateCoupon(info, cid, Integer.parseInt(goods.getPrice())).getMoney());

            Coupond = Integer.parseInt(coupon.getMoney());

            //需要的积分不等于0 判断商品积分
            if (Integer.parseInt(goods.getIntegral()) > 0) {
                GETUserByOpenid getUserByOpenid = new GETUserByOpenid(info.getUrl(), info.getAccount(), info.getPassword());
                int integral = Integer.parseInt(getUserByOpenid.getData(openid).getIntegral());
                if (Integer.parseInt(goods.getIntegral()) > integral) {
                    throw new OrderExceptionApp("创建订单失败！积分不足！");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new OrderExceptionApp(e.getMessage());
        }
        // 创建当前时间对象

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String now = sdf.format(date);
        //创建订单Order对象
        Order order = new Order();
        order.setUid(uid);


        //计算价格
        rp = ActualPayment(rp, 0, Coupond);
        System.err.println(rp);

        //实际价格
        BigDecimal sjjg = BigDecimal.valueOf(rp);

        ArrayList<ArrayList> RETAIL = new ArrayList<>();
        //**********************************
        //零售单明细
        ArrayList list = new ArrayList();
        list.add(code);
        list.add(1);
        list.add(sjjg);
        RETAIL.add(list);
        String orderType = "Z";
        //积分调整接口商品积分大于0时执行

        if (Integer.parseInt(goods.getIntegral()) > 0) {

            CreateIntegral createIntegral = new CreateIntegral(info.getUrl(), info.getAccount(), info.getPassword());
            //HashMap<String, String> integralmap = null;
            try {
                //integralmap = createIntegral.getData(phone, good.getIntegral());
                //order.setIntegralCode(integralmap.get("code"));
                order.setIntegralCode(createIntegral.getData(phone, goods.getIntegral()));
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.getMessage());
                order.setIntegralMessage(e.getMessage());
                throw new OrderExceptionApp("积分调整单错误" + e.getMessage());
            }
        }

        //零售单
        //CreateRetall createRetall = new CreateRetall(info.getUrl(), info.getAccount(), info.getPassword());
        CreateYCRETAIL_ZT createYCRETAIL_ZT = new CreateYCRETAIL_ZT(info.getUrl(), info.getAccount(), info.getPassword());
        //FindStoreData findStoreData = new FindStoreData(info.getUrl(), info.getAccount(), info.getPassword());

        try {//orderType  Z:正常订单,S:秒杀订单,P:拼团订单,K:砍价订单,Y:预售订单,
            //计算距离
//            ArrayList<Store> stores = findStoreData.getData();
//
//            CalculatStoreSpaceDistance(Double.parseDouble(address.getLongitude()), Double.parseDouble(address.getLatitude()), stores);
              String row = createYCRETAIL_ZT.getData(orderType, RETAIL, store, distance, phoneZT, nameZT, sjjg.toString(), phone, orderid, coupon, self + "", dateZT, emp, comment);
            order.setRetailCode(row);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            order.setRetailMessage(e.getMessage());
            throw new OrderExceptionApp("零售单错误" + e.getMessage());
        }
        // 向Order对象封装receiver,phone,address
        order.setReceiver(nameZT);
        order.setPhone(phone);
        order.setAddress("会员自提:" + store);
        // 向Order对象封装state值为0
        order.setState("0");
        order.setOrderTime(now);
        order.setTotalPrice(String.valueOf(sjjg));
        order.setTotalIntegral(goods.getIntegral());
        order.setCreatedUser(phone);
        order.setCreatedTime(now);
        order.setModifiedUser(phone);
        order.setModifiedTime(now);
        order.setToken(token);
        order.setAccount(token);
        //封装订单号
        order.setOrderId(orderid);
        order.setMailFee("0");
        order.setSelf(self+"");
        // 执行插入订单数据
        insertOrder(order);

        OrderItem item = new OrderItem();
        // 向OrderItem对象中封装商品相关的5个数据
        item.setGoodsId(goods.getId());
        item.setGoodsTitle(goods.getName());
        item.setGoodsImage(goods.getImg());
        item.settName(type);
        item.setCode(code);
        item.setGoodsPrice(sjjg.toString());
        item.setGoodsIntegral(goods.getIntegral());
        item.setGoodsNum("1");
        // 向OrderItem对象中封装oid：order.getOid()
        item.setOid(order.getId());
        // 向OrderItem对象中封装日志
        item.setCreatedUser(phone);
        item.setCreatedTime(now);
        item.setModifiedUser(phone);
        item.setModifiedTime(now);
        // 执行插入订单商品数据
        insertOrderItem(item);
      //  sjjg = MathUtil.add(sjjg, BigDecimal.valueOf(Integer.parseInt(mail.getPrice())), 0);
        //生成支付
        if (null != cid) {
            UseCoupon(cid, info);//核销优惠券
        }

        PayData data = new PayData();
        System.err.println(sjjg);
        if (sjjg.doubleValue() > 0) {
            try {
                String notify_url = "https://lfwd.cloudsmicro.com/shop/pay/result";
                data = payWechatService.createUnified(notify_url, openid, token, order.getOrderId(), sjjg.toString(), goods.getName());
                data.setOrderId(order.getId());

            } catch (Exception e) {
                e.printStackTrace();
                throw new OrderExceptionApp(e.getMessage());
            }
            data.setType("price");
        } else {
            //纯积分支付
            integralPay(info, order, data);
        }
        return data;



    }

    /**
     * 秒杀自提
     * @param uid
     * @param openid
     * @param phoneZT
     * @param nameZT
     * @param sid
     * @param code
     * @param store
     * @param distance
     * @param dateZT
     * @param type
     * @param phone
     * @param token
     * @param emp
     * @param comment
     * @return
     * @throws OrderExceptionApp
     */
    @Override
    public PayData seckillCreateOrderZT(String uid, String openid, String phoneZT, String nameZT, String sid, String code, String store, String distance, String dateZT, String type, String phone, String token, String emp, String comment) throws OrderExceptionApp {
        Date date = new Date();
        Seckill seckill = seckillMapper.getDataById(sid);
        Info info = GetInfo(token);
        String orderid = getOrderIdByUUId();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String now = sdf.format(new Date());
        SimpleDateFormat sdfe = new SimpleDateFormat("yyyy/MM/dd" + " " + "HH:mm:ss");
        try {
            if (date.getTime() > (sdfe.parse(seckill.getDateend())).getTime()
                    &&!"Y".equals(seckill.getPutaway())
            ) {
                throw new OrderExceptionApp("活动已过期");
            }
        } catch (ParseException e) {
            throw new OrderExceptionApp(e.getMessage());
        }
        determineTheInventory(info, code, 1);
        Goods goods = goodsService.findGoodsById(seckill.getGid(), uid, "1", "N");
        Order order = new Order();
        order.setUid(uid);

        //零售单明细
        ArrayList<ArrayList> RETAIL = new ArrayList<>();
        ArrayList list = new ArrayList();
        list.add(code);
        list.add(1);
        list.add(goods.getPrice());
        RETAIL.add(list);
        //积分调整接口商品积分大于0时执行
        if (Integer.parseInt(goods.getIntegral()) > 0) {
            CreateIntegral createIntegral = new CreateIntegral(info.getUrl(), info.getAccount(), info.getPassword());
            try {
                order.setIntegralCode(createIntegral.getData(phone, goods.getIntegral()));
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.getMessage());
                order.setIntegralMessage(e.getMessage());
                throw new OrderExceptionApp("积分调整单错误" + e.getMessage());
            }
        }

        CreateYCRETAIL_ZT createYCRETAIL_ZT = new CreateYCRETAIL_ZT(info.getUrl(), info.getAccount(), info.getPassword());

        Coupon coupon = new Coupon();
        coupon.setMoney("0");
        int self = new Random().nextInt(9000000) + 1000000;
        try {//orderType  Z:正常订单,S:秒杀订单,P:拼团订单,K:砍价订单,Y:预售订单,

            String row = createYCRETAIL_ZT.getData("S", RETAIL, store, distance, phoneZT, nameZT, goods.getPrice(), phone, orderid, coupon, self + "", dateZT, emp, comment);
            order.setRetailCode(row);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            order.setRetailMessage(e.getMessage());
            throw new OrderExceptionApp("零售单错误" + e.getMessage());
        }
        // 向Order对象封装receiver,phone,address
        order.setReceiver(nameZT);
        order.setPhone(phone);
        order.setAddress("会员自提:" + store);
        // 向Order对象封装state值为0
        order.setState("0");
        order.setOrderTime(now);
        order.setTotalPrice(goods.getPrice());
        order.setTotalIntegral(goods.getIntegral());
        order.setCreatedUser(phone);
        order.setCreatedTime(now);
        order.setModifiedUser(phone);
        order.setModifiedTime(now);
        order.setToken(token);
        order.setAccount(token);
        order.setSelf(String.valueOf(self));
        //封装订单号
        order.setOrderId(orderid);
        order.setMailFee("0");
        // 执行插入订单数据
        insertOrder(order);

        OrderItem item = new OrderItem();
        // 向OrderItem对象中封装商品相关的5个数据
        item.setGoodsId(goods.getId());
        item.setGoodsTitle(goods.getName());
        item.setGoodsImage(goods.getImg());
        item.settName(type);
        item.setCode(code);
        item.setGoodsPrice(goods.getPrice());
        item.setGoodsIntegral(goods.getIntegral());
        item.setGoodsNum("1");
        // 向OrderItem对象中封装oid：order.getOid()
        item.setOid(order.getId());
        // 向OrderItem对象中封装日志
        item.setCreatedUser(phone);
        item.setCreatedTime(now);
        item.setModifiedUser(phone);
        item.setModifiedTime(now);
        // 执行插入订单商品数据
        insertOrderItem(item);
        PayData data = new PayData();
        System.err.println(goods.getPrice());
        if (Integer.parseInt(goods.getPrice()) > 0) {
            try {
                String notify_url = "https://lfwd.cloudsmicro.com/shop/pay/result";
                data = payWechatService.createUnified(notify_url, openid, token, order.getOrderId(), goods.getPrice(), goods.getName());
                data.setOrderId(order.getId());

            } catch (Exception e) {
                e.printStackTrace();
                throw new OrderExceptionApp(e.getMessage());
            }
            data.setType("price");
        } else {
            //纯积分支付
            integralPay(info, order, data);
        }

        data.setSelf(String.valueOf(self));


        return data;
    }

    /**
     * 支付尾款
     *
     * @param order
     * @param address
     * @param phone
     * @param mail
     * @param comment
     * @param openid
     * @param token
     * @return
     * @throws OrderExceptionApp
     */
    @Override
    public PayData payForThebalance(Order order, Address address, String phone, Mail mail,
                                    String comment, String openid, String token) throws OrderExceptionApp {

        //生成云仓订单

        //生成支付
        //Order order = orderMapper.FindOrder(oid);
        StringBuffer title = new StringBuffer();

        Info info = GetInfo(token);
        CreateYCRETAIL createYCRETAIL = new CreateYCRETAIL(info.getUrl(), info.getAccount(), info.getPassword());
        FindStoreData findStoreData = new FindStoreData(info.getUrl(), info.getAccount(), info.getPassword());
        ArrayList<ArrayList> RETAIL = new ArrayList<>();
        //**********************************
        //零售单明细
        ArrayList list = new ArrayList();
        List<OrderItem> orderItems = orderMapper.FindOrderItemByOid(order.getId());
        String sjjg = String.valueOf(Integer.parseInt(order.getTotalPrice()) + Integer.parseInt(order.getEarnest()));
        list.add(orderItems.get(0).getCode());
        list.add(1);
        list.add(sjjg);
        RETAIL.add(list);
        ModRefundState modRefundState = new ModRefundState(info.getUrl(), info.getAccount(), info.getPassword());

        try {//orderType  Z:正常订单,S:秒杀订单,P:拼团订单,K:砍价订单,Y:预售订单,
            //计算距离

            if (null == order.getRetailCode()) {
                ArrayList<Store> stores = findStoreData.getData();

                CalculatStoreSpaceDistance(Double.parseDouble(address.getLongitude()), Double.parseDouble(address.getLatitude()), stores);
                String row = createYCRETAIL.getData("Y", RETAIL, sjjg, phone, order.getOrderId(), mail, address, null, stores, comment, order.getEmp());

                orderMapper.upOrderYCRetail(order.getId(), row);

            } else {
                order.setOrderId(getOrderIdByUUId());

                //修改预售单 订单 云仓订单 云仓预售单
                  orderMapper.upOrderCodeById(order.getId(), order.getOrderId());
                modRefundState.getData(order.getRetailCode(), "YC_RETAIL", "XSNO", order.getOrderId());

            }
            //写入预售单号
            modRefundState.getData(order.getRetailCode(),"YC_RETAIL","YSXSNO",order.getEarnestOrderId());


        } catch (Exception e) {
            e.printStackTrace();
            throw new OrderExceptionApp(e.getMessage());
        }

        PayData data = new PayData();

        double tot = Double.parseDouble(order.getTotalPrice()) + Double.parseDouble(order.getMailFee());

        try {
            String notify_url = "https://lfwd.cloudsmicro.com/shop/pay/result";
            data = payWechatService.createUnified(notify_url, openid, token, order.getOrderId(),
                    Double.toString(tot).replace(".00", "")
                            .replace(".0", "").trim()
                    , String.valueOf(title));
            //返回
            data.setOrderId(order.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        data.setType("price");


        return data;
    }

    @Override
    public Integer NumberOfDaysOfSelfPickupDelay(String token) {
        Integer data = orderMapper.NumberOfDaysOfSelfPickupDelay(token);
        if (data == null) {
            data = 0;
        }
        return data;
    }

    //积分自提
    @Override
    public PayData integralCreateOrderZT(String uid, String openid, String phoneZT, String nameZT,
                                         String gid, String code, String store, String distance,
                                         String dateZT, String type, String phone, String token, String emp, String comment) throws OrderExceptionApp {
        Info info = GetInfo(token);
        Goods goods = goodsService.findGoodsById(gid, uid, "1", "N");

        String orderid = getOrderIdByUUId();

        try {

            //需要的积分不等于0 判断商品积分
            if (Integer.parseInt(goods.getIntegral()) > 0) {
                GETUserByOpenid getUserByOpenid = new GETUserByOpenid(info.getUrl(), info.getAccount(), info.getPassword());
                int integral = Integer.parseInt(getUserByOpenid.getData(openid).getIntegral());
                if (Integer.parseInt(goods.getIntegral()) > integral) {
                    throw new OrderExceptionApp("创建订单失败！积分不足！");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new OrderExceptionApp(e.getMessage());
        }
        // 创建当前时间对象
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String now = sdf.format(new Date());
        //创建订单Order对象
        Order order = new Order();
        order.setUid(uid);

        //零售单明细
        ArrayList<ArrayList> RETAIL = new ArrayList<>();
        ArrayList list = new ArrayList();
        list.add(code);
        list.add(1);
        list.add(goods.getPrice());
        RETAIL.add(list);
        //积分调整接口商品积分大于0时执行
        if (Integer.parseInt(goods.getIntegral()) > 0) {
            CreateIntegral createIntegral = new CreateIntegral(info.getUrl(), info.getAccount(), info.getPassword());
            try {
                order.setIntegralCode(createIntegral.getData(phone, goods.getIntegral()));
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.getMessage());
                order.setIntegralMessage(e.getMessage());
                throw new OrderExceptionApp("积分调整单错误" + e.getMessage());
            }
        }

        CreateYCRETAIL_ZT createYCRETAIL_ZT = new CreateYCRETAIL_ZT(info.getUrl(), info.getAccount(), info.getPassword());

        Coupon coupon = new Coupon();
        coupon.setMoney("0");
        int self = new Random().nextInt(9000000) + 1000000;
        try {//orderType  Z:正常订单,S:秒杀订单,P:拼团订单,K:砍价订单,Y:预售订单,

            String row = createYCRETAIL_ZT.getData("J", RETAIL, store, distance, phoneZT, nameZT, goods.getPrice(), phone, orderid, coupon, self + "", dateZT, emp, comment);
            order.setRetailCode(row);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            order.setRetailMessage(e.getMessage());
            throw new OrderExceptionApp("零售单错误" + e.getMessage());
        }
        // 向Order对象封装receiver,phone,address
        order.setReceiver(nameZT);
        order.setPhone(phone);
        order.setAddress("会员自提:" + store);
        // 向Order对象封装state值为0
        order.setState("0");
        order.setOrderTime(now);
        order.setTotalPrice(goods.getPrice());
        order.setTotalIntegral(goods.getIntegral());
        order.setCreatedUser(phone);
        order.setCreatedTime(now);
        order.setModifiedUser(phone);
        order.setModifiedTime(now);
        order.setToken(token);
        order.setAccount(token);
        order.setSelf(String.valueOf(self));
        //封装订单号
        order.setOrderId(orderid);
        order.setMailFee("0");
        // 执行插入订单数据
        insertOrder(order);

        OrderItem item = new OrderItem();
        // 向OrderItem对象中封装商品相关的5个数据
        item.setGoodsId(goods.getId());
        item.setGoodsTitle(goods.getName());
        item.setGoodsImage(goods.getImg());
        item.settName(type);
        item.setCode(code);
        item.setGoodsPrice(goods.getPrice());
        item.setGoodsIntegral(goods.getIntegral());
        item.setGoodsNum("1");
        // 向OrderItem对象中封装oid：order.getOid()
        item.setOid(order.getId());
        // 向OrderItem对象中封装日志
        item.setCreatedUser(phone);
        item.setCreatedTime(now);
        item.setModifiedUser(phone);
        item.setModifiedTime(now);
        // 执行插入订单商品数据
        insertOrderItem(item);

        //生成支付

        PayData data = new PayData();
        System.err.println(goods.getPrice());
        if (Integer.parseInt(goods.getPrice()) > 0) {
            try {
                String notify_url = "https://lfwd.cloudsmicro.com/shop/pay/result";
                data = payWechatService.createUnified(notify_url, openid, token, order.getOrderId(), goods.getPrice(), goods.getName());
                data.setOrderId(order.getId());

            } catch (Exception e) {
                e.printStackTrace();
                throw new OrderExceptionApp(e.getMessage());
            }
            data.setType("price");
        } else {
            //纯积分支付
            integralPay(info, order, data);
        }

        data.setSelf(String.valueOf(self));
        return data;
    }

    //积分付款
    @Override
    public PayData integralCreateOrder(String uid, String openid, String aid, String mid,
                                       String gid, String code, String type,
                                       String phone, String token, String comment, String emp) throws OrderExceptionApp {

        Info info = GetInfo(token);
        Goods goods = goodsService.findGoodsById(gid, uid, "1", "N");

        Mail mail = new Mail();

        if ("-1".equals(mid)) {//包邮
            mail.setPrice("0");
            mail.setName("包邮");
        } else {
            mail = mailService.GetMail(mid);
        }
        Date date = new Date();
        String orderid = getOrderIdByUUId();
        //计算满减价格

        try {

            //需要的积分不等于0 判断商品积分
            if (Integer.parseInt(goods.getIntegral()) > 0) {
                GETUserByOpenid getUserByOpenid = new GETUserByOpenid(info.getUrl(), info.getAccount(), info.getPassword());
                int integral = Integer.parseInt(getUserByOpenid.getData(openid).getIntegral());
                if (Integer.parseInt(goods.getIntegral()) > integral) {
                    throw new OrderExceptionApp("创建订单失败！积分不足！");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new OrderExceptionApp(e.getMessage());
        }
        // 创建当前时间对象
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String now = sdf.format(date);
        //创建订单Order对象
        Order order = new Order();
        order.setUid(uid);
        // 根据aid查询地址数据：addressService.getByAid(aid)
        Address address = addressService.getAddressById(aid);
        // 判断查询结果，如果为null，抛出异常
        if (address == null) {
            throw new OrderExceptionApp("创建订单失败！收货地址数据不存在！");
        }
        //计算价格


        ArrayList<ArrayList> RETAIL = new ArrayList<>();
        //**********************************
        //零售单明细
        ArrayList list = new ArrayList();
        list.add(code);
        list.add(1);
        list.add(goods.getPrice());
        RETAIL.add(list);
        //积分调整接口商品积分大于0时执行
        if (Integer.parseInt(goods.getIntegral()) > 0) {
            CreateIntegral createIntegral = new CreateIntegral(info.getUrl(), info.getAccount(), info.getPassword());

            try {

                order.setIntegralCode(createIntegral.getData(phone, goods.getIntegral()));
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.getMessage());
                order.setIntegralMessage(e.getMessage());
                throw new OrderExceptionApp("积分调整单错误" + e.getMessage());
            }
        }

        CreateYCRETAIL createYCRETAIL = new CreateYCRETAIL(info.getUrl(), info.getAccount(), info.getPassword());
        FindStoreData findStoreData = new FindStoreData(info.getUrl(), info.getAccount(), info.getPassword());

        try {//orderType  Z:正常订单,S:秒杀订单,P:拼团订单,K:砍价订单,Y:预售订单,
            //计算距离
            ArrayList<Store> stores = findStoreData.getData();

            CalculatStoreSpaceDistance(Double.parseDouble(address.getLongitude()), Double.parseDouble(address.getLatitude()), stores);
            String row = createYCRETAIL.getData("J", RETAIL, goods.getPrice(), phone, orderid, mail, address, null, stores, comment, emp);
            order.setRetailCode(row);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            order.setRetailMessage(e.getMessage());
            throw new OrderExceptionApp("零售单错误" + e.getMessage());
        }
        // 向Order对象封装receiver,phone,address
        order.setReceiver(address.getReceiver());
        order.setPhone(address.getPhone());
        order.setAddress(address.getAddress());
        // 向Order对象封装state值为0
        order.setState("0");
        order.setOrderTime(now);
        order.setTotalPrice(goods.getPrice());
        order.setTotalIntegral(goods.getIntegral());
        order.setCreatedUser(phone);
        order.setCreatedTime(now);
        order.setModifiedUser(phone);
        order.setModifiedTime(now);
        order.setToken(token);
        order.setAccount(token);
        //封装订单号
        order.setOrderId(orderid);
        order.setMailFee(mail.getPrice());
        // 执行插入订单数据
        insertOrder(order);

        OrderItem item = new OrderItem();
        // 向OrderItem对象中封装商品相关的5个数据
        item.setGoodsId(goods.getId());
        item.setGoodsTitle(goods.getName());
        item.setGoodsImage(goods.getImg());
        item.settName(type);
        item.setCode(code);
        item.setGoodsPrice(goods.getPrice());
        item.setGoodsIntegral(goods.getIntegral());
        item.setGoodsNum("1");
        // 向OrderItem对象中封装oid：order.getOid()
        item.setOid(order.getId());
        // 向OrderItem对象中封装日志
        item.setCreatedUser(phone);
        item.setCreatedTime(now);
        item.setModifiedUser(phone);
        item.setModifiedTime(now);
        // 执行插入订单商品数据
        insertOrderItem(item);

        BigDecimal sjjg = MathUtil.add(new BigDecimal(goods.getPrice()), BigDecimal.valueOf(Integer.parseInt(mail.getPrice())), 0);


        PayData data = new PayData();
        System.err.println(sjjg);
        if (sjjg.doubleValue() > 0) {
            try {
                String notify_url = "https://lfwd.cloudsmicro.com/shop/pay/result";
                data = payWechatService.createUnified(notify_url, openid, token, order.getOrderId(), sjjg.toString(), goods.getName());
                data.setOrderId(order.getId());

            } catch (Exception e) {
                e.printStackTrace();
                throw new OrderExceptionApp(e.getMessage());
            }
            data.setType("price");
        } else {
            //纯积分支付
            integralPay(info, order, data);
        }
        return data;
    }

    @Override
    public PayData seckillCreateOrder(String uid, String openid, String aid, String mid,
                                      String sid, String cid, String code, String type,
                                      String phone, String token, String comment, String emp)
            throws OrderExceptionApp {

        Date date = new Date();
        System.err.println("mid=" + mid);
        Seckill seckill = seckillMapper.getDataById(sid);
        SimpleDateFormat sdfe = new SimpleDateFormat("yyyy/MM/dd" + " " + "HH:mm:ss");
        try {
            if (date.getTime() > (sdfe.parse(seckill.getDateend())).getTime()
            &&!"Y".equals(seckill.getPutaway())
            ) {
                throw new OrderExceptionApp("时间已过期");
            }
        } catch (ParseException e) {
            throw new OrderExceptionApp(e.getMessage());
        }
        Info info = GetInfo(token);
        Goods goods = goodsService.findGoodsById(seckill.getGid(), uid, "1", "N");
        //判断库存
        determineTheInventory(info, code, 1);
        Mail mail = new Mail();

        if ("-1".equals(mid)) {//包邮
            mail.setPrice("0");
            mail.setName("包邮");
        } else if ("-2".equals(mid)) {//积分减免
            QuerryMailFee querryMailFee = new QuerryMailFee(info.getUrl(), info.getAccount(), info.getPassword());
            String row = null;
            try {
                row = querryMailFee.getData(phone);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if ("null".equals(row) || null == row) {
                throw new OrderExceptionApp("出现错误,抵扣运费null");
            } else {

                goods.setIntegral(String.valueOf(Integer.parseInt(goods.getIntegral()) + Integer.parseInt(row)));
                mail.setPrice("0");
            }
        } else {
            mail = mailService.GetMail(mid);
        }
        System.err.println(goods.getIntegral());


        String orderid = getOrderIdByUUId();

        //计算满减价格
        List<Goods> goodsList = new ArrayList<>();
        if (null != goods.getActivityId() && !"0".equals(goods.getActivityId())) {
            goods.setActivitieitem(appActivityService.getActvityById(goods.getActivityId()));
            if (null == goods.getActivitieitem() || !"N".equals(goods.getActivitieitem().getIsUse())) {
                goodsList.add(goods);
            }
        }

        int rp = goodsActivity(Integer.parseInt(seckill.getPrice()), goodsList);

        //优惠券金额
        int Coupond;
        Coupon coupon = calculateCoupon(info, cid, Integer.parseInt(seckill.getPrice()));
        try {
            //判断优惠券是否可用 是 返回金额 否 返回异常
            //Coupond = Integer.parseInt(calculateCoupon(info, cid, Integer.parseInt(goods.getPrice())).getMoney());

            Coupond = Integer.parseInt(coupon.getMoney());

            //需要的积分不等于0 判断会员积分
            if (Integer.parseInt(goods.getIntegral()) > 0) {
                GETUserByOpenid getUserByOpenid = new GETUserByOpenid(info.getUrl(), info.getAccount(), info.getPassword());
                int integral = Integer.parseInt(getUserByOpenid.getData(openid).getIntegral());
                if (Integer.parseInt(goods.getIntegral()) > integral) {
                    throw new OrderExceptionApp("创建订单失败！积分不足！");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new OrderExceptionApp(e.getMessage());
        }
        // 创建当前时间对象

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String now = sdf.format(date);
        //创建订单Order对象
        Order order = new Order();
        order.setUid(uid);

        // 根据aid查询地址数据：addressService.getByAid(aid)
        Address address = addressService.getAddressById(aid);
        // 判断查询结果，如果为null，抛出异常
        if (address == null) {
            throw new OrderExceptionApp("创建订单失败！收货地址数据不存在！");
        }


        //计算价格
        rp = ActualPayment(rp, 0, Coupond);
        System.err.println(rp);

        //实际价格
        BigDecimal sjjg = BigDecimal.valueOf(rp);

        ArrayList<ArrayList> RETAIL = new ArrayList<>();
        //**********************************
        //零售单明细
        ArrayList list = new ArrayList();
        list.add(code);
        list.add(1);
        list.add(sjjg);
        RETAIL.add(list);

        //积分调整接口商品积分大于0时执行
        if (Integer.parseInt(goods.getIntegral()) > 0) {
            CreateIntegral createIntegral = new CreateIntegral(info.getUrl(), info.getAccount(), info.getPassword());
            //HashMap<String, String> integralmap = null;
            try {
                //integralmap = createIntegral.getData(phone, good.getIntegral());
                //order.setIntegralCode(integralmap.get("code"));
                order.setIntegralCode(createIntegral.getData(phone, goods.getIntegral()));
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.getMessage());
                order.setIntegralMessage(e.getMessage());
                throw new OrderExceptionApp("积分调整单错误" + e.getMessage());
            }
        }

        //零售单
        //CreateRetall createRetall = new CreateRetall(info.getUrl(), info.getAccount(), info.getPassword());
        CreateYCRETAIL createYCRETAIL = new CreateYCRETAIL(info.getUrl(), info.getAccount(), info.getPassword());
        FindStoreData findStoreData = new FindStoreData(info.getUrl(), info.getAccount(), info.getPassword());

        try {//orderType  Z:正常订单,S:秒杀订单,P:拼团订单,K:砍价订单,Y:预售订单,
            //计算距离
            ArrayList<Store> stores = findStoreData.getData();

            CalculatStoreSpaceDistance(Double.parseDouble(address.getLongitude()), Double.parseDouble(address.getLatitude()), stores);
            String row = createYCRETAIL.getData("S", RETAIL, sjjg.toString(), phone, orderid, mail, address, coupon, stores, comment, emp);
            order.setRetailCode(row);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            order.setRetailMessage(e.getMessage());
            throw new OrderExceptionApp("零售单错误" + e.getMessage());
        }
        // 向Order对象封装receiver,phone,address
        order.setReceiver(address.getReceiver());
        order.setPhone(address.getPhone());
        order.setAddress(address.getAddress());
        // 向Order对象封装state值为0
        order.setState("0");
        order.setOrderTime(now);
        order.setTotalPrice(String.valueOf(sjjg));
        order.setTotalIntegral(goods.getIntegral());
        order.setCreatedUser(phone);
        order.setCreatedTime(now);
        order.setModifiedUser(phone);
        order.setModifiedTime(now);
        order.setToken(token);
        order.setAccount(token);
        //封装订单号
        order.setOrderId(orderid);
        order.setMailFee(mail.getPrice());
        // 执行插入订单数据
        insertOrder(order);

        OrderItem item = new OrderItem();
        // 向OrderItem对象中封装商品相关的5个数据
        item.setGoodsId(goods.getId());
        item.setGoodsTitle(goods.getName());
        item.setGoodsImage(goods.getImg());
        item.settName(type);
        item.setCode(code);
        item.setGoodsPrice(sjjg.toString());
        item.setGoodsIntegral(goods.getIntegral());
        item.setGoodsNum("1");
        // 向OrderItem对象中封装oid：order.getOid()
        item.setOid(order.getId());
        // 向OrderItem对象中封装日志
        item.setCreatedUser(phone);
        item.setCreatedTime(now);
        item.setModifiedUser(phone);
        item.setModifiedTime(now);
        // 执行插入订单商品数据
        insertOrderItem(item);
        sjjg = MathUtil.add(sjjg, BigDecimal.valueOf(Integer.parseInt(mail.getPrice())), 0);
        //生成支付
        if (null != cid) {
            UseCoupon(cid, info);//核销优惠券
        }

        PayData data = new PayData();
        System.err.println(sjjg);
        if (sjjg.doubleValue() > 0) {
            try {
                String notify_url = "https://lfwd.cloudsmicro.com/shop/pay/result";
                data = payWechatService.createUnified(notify_url, openid, token, order.getOrderId(), sjjg.toString(), goods.getName());
                data.setOrderId(order.getId());
            } catch (Exception e) {
                e.printStackTrace();
                throw new OrderExceptionApp(e.getMessage());
            }
            data.setType("price");
        } else {
            //纯积分支付
            integralPay(info, order, data);
        }
        return data;


    }

    @Override
    public void DelOrder(String id, String token) {
        try {
            orderMapper.DelOrderById(id, token);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //收货
    @Override
    public void UpOrderState(String id, String token) {
        try {
            Order order = orderMapper.FindOrderERPData(id);
            //订单编号查询id
            Info info = GetInfo(token);
            FIndYCRETALLByCode fIndYCRETALLByCode = new FIndYCRETALLByCode(info.getUrl(), info.getAccount(), info.getPassword());
            String Rid = fIndYCRETALLByCode.getData(order.getRetailCode());

            //修改云仓 云仓派单状态同步
            ModRefundState modRefundState = new ModRefundState(info.getUrl(), info.getAccount(), info.getPassword());
            modRefundState.getData(Rid, "YC_MRETAIL", "IS_INGOODS", "Y");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
            orderMapper.UpOrderStateById(id, "3", token,sdf.format(new Date()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    @Transactional
    public PayData payForTheOrder(String oid, String openid, String token) throws OrderExceptionApp {

        Order order = orderMapper.FindOrder(oid);
        StringBuffer title = new StringBuffer();
        order.setOrderId(getOrderIdByUUId());
        Info info = GetInfo(token);
        //修改erp orderid
        ModRefundState modRefundState = new ModRefundState(info.getUrl(), info.getAccount(), info.getPassword());
        orderMapper.upOrderCodeById(order.getId(), order.getOrderId());

        QueryStorage queryStorage = new QueryStorage(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            modRefundState.getData(order.getRetailCode(), "YC_RETAIL", "XSNO", order.getOrderId());
            for (OrderItem orderItem : order.getOrderItems()) {
                int count = queryStorage.getData(orderItem.getCode());
                if (Integer.parseInt(orderItem.getGoodsNum()) > count) {
                    throw new OrderExceptionApp("创建订单失败！库存数量不足！");
                }
                title.append(orderItem.getGoodsTitle()).append("*").append(orderItem.getGoodsNum()).append(";");
            }
            //需要的积分不等于0 判断会员积分
            if (Integer.parseInt(order.getTotalIntegral()) > 0) {
                GETUserByOpenid getUserByOpenid = new GETUserByOpenid(info.getUrl(), info.getAccount(), info.getPassword());
                int integral = Integer.parseInt(getUserByOpenid.getData(openid).getIntegral());
                if (Integer.parseInt(order.getTotalIntegral()) > integral) {
                    throw new OrderExceptionApp("支付失败失败！积分不足！");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new OrderExceptionApp(e.getMessage());
        }

        PayData data = new PayData();
        Order orderMail = orderMapper.FindOrderMail(order.getId());
        double tot = Double.parseDouble(order.getTotalPrice()) + Double.parseDouble(orderMail.getMailFee());
        if (tot > 0) {
            System.err.println("*******************");
            System.err.println(tot);
            try {
                String notify_url = "https://lfwd.cloudsmicro.com/shop/pay/result";
                data = payWechatService.createUnified(notify_url, openid, token, order.getOrderId(),
                        Double.toString(tot).replace(".00", "")
                                .replace(".0", "").trim()
                        , String.valueOf(title));
                //返回
                data.setOrderId(order.getId());
            } catch (Exception e) {
                e.printStackTrace();
            }
            data.setType("price");
        } else {    //金额为0 不发起支付 提交单据完成交易
            integralPay(info, order, data);
            data.setOrderId(order.getId());
        }

        return data;
    }

    @Override
    public OrderResult GetLatestOrder(String oid, String uid, String token) {
        String result = "支付成功";
        Order order = orderMapper.FindLatestOrder(oid, uid, token);
        OrderResult orderResult = new OrderResult();
        orderResult.setState("SUCCESS");
        if ("0".equals(order.getState())) {
            result = order.getRetailMessage() + "," + order.getIntegralMessage();
            orderResult.setState("ERROR");
        } else if ("-1".equals(order.getState())) {
            result = "支付取消";
            orderResult.setState("ERROR");
        }
        List<OrderItem> orderItems = orderMapper.FindOrderItemByOid(order.getId());
        StringBuffer stringBuffer = new StringBuffer();
        for (OrderItem orderItem : orderItems) {
            stringBuffer.append(orderItem.getGoodsTitle()).append("*").append(orderItem.getGoodsNum()).append(";");
        }
        orderResult.setPrice(order.getTotalPrice());
        orderResult.setIntegral(order.getTotalIntegral());
        orderResult.setOid(order.getId());
        orderResult.setGoods(String.valueOf(stringBuffer));
        orderResult.setOrderId(order.getOrderId());
        orderResult.setDate(order.getOrderTime());
        orderResult.setAddress(order.getAddress());
        orderResult.setPhone(order.getPhone());
        orderResult.setReceiver(order.getReceiver());
        orderResult.setMessage(result.replace("null", ""));
        //发送客服消息********************************************************
        if ("1".equals(order.getState())) {
            //企业微信新订单通知
            queueService.sendEWEmpNewOrder(uid,order.getRetailCode(),token);
            try {
                //获取订单信息 会员电话 会员名 推送的客服名称 订单号 token
                //获取要发送的openid
                ArrayList<ShopKf> shopKfs = weChatKfMapper.getKf(order.getToken());
                //判断发送订单消息/积分兑换消息
                for (ShopKf shopKf : shopKfs) {
                    if (Integer.parseInt(order.getTotalIntegral()) > 0) {
                        //积分兑换
                        empNotificationMessageService.sendEmpCreditsExchange("客服", order.getName(), order.getPhone(),
                                shopKf.getOpenid(), order.getRetailCode(), order.getToken());
                    } else {
                        empNotificationMessageService.sendEmpNewOrder(
                                "客服", order.getName(), order.getPhone(),
                                shopKf.getOpenid(), order.getRetailCode(), order.getToken());
                    }
                }

            } catch (Exception e) {
                logger.error(e.getMessage());
                e.printStackTrace();
            }
        }

        return orderResult;
    }

    @Override
    public void UpERPData(Order order) {
        try {
            orderMapper.UpERTData(order);
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("修改提交状态出错");
        }
    }

    @Override
    public Order FindOrderByCode(String code) {
        return orderMapper.FindOrderERPByCode(code);
    }

    @Override
    public Order FindOrder(String id) {
        Order orderMail = orderMapper.FindOrderMail(id);
        Order order = orderMapper.FindOrder(id);
        order.setMailFee(orderMail.getMailFee());
        return order;
    }

    @Override
    public List<Order> getUserOrder(String uid, String token) {
        List<Order> data = orderMapper.GetOrderByUid(uid, token);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        int now = Integer.parseInt(sdf.format(new Date()));
        //判断预售订单
        for (Order order : data) {
            if ("YS".equals(order.getOrderType())) {
                Presell presell = orderMapper.FindPresellByOid(order.getId());
                if (null != presell &&  null != presell.getClearingTime()
                        && now >= Integer.parseInt(presell.getClearingTime())
                        && now < Integer.parseInt(presell.getEndTime())
                        && "-1".equals(order.getState())
                ) {
                    order.setState("0");
                    order.setPresellEndTime(presell.getEndTime());
                    order.setPid(presell.getId());
                    order.setTotalPrice(String.valueOf(Integer.parseInt(order.getTotalPrice()) - Integer.parseInt(presell.getRem())));
                }
            }

        }
        return data;
    }

    @Override
    public HashMap<String, Integer> getWebOrderCount(String uid, String token) {

        //获取正在退货数量
        Integer Rcount = orderMapper.findRefundInProgress(token, uid);
        List<Order> orders = orderMapper.GetOrderByUid(uid, token);

        int dfk = 0;
        int dfh = 0;
        int yfh = 0;
        int dpj = 0;
        int ypj = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String now = sdf.format(new Date());
        for (Order order : orders) {
            switch (order.getState()) {
                case "-1":
                    if ("YS".equals(order.getOrderType())) {
                        Presell presell = orderMapper.FindPresellByOid(order.getId());
                        if (null != presell && null!=presell.getEndTime()
                                //    && Integer.parseInt(now) >= Integer.parseInt(presell.getClearingTime())
                                && Integer.parseInt(now) < Integer.parseInt(presell.getEndTime())
                                && "-1".equals(order.getState())
                        ) {
                            dfk += 1;
                        }
                    }
                    break;
                case "0":
                    if ("0".equals(order.getState())
                            && !now.equals(order.getOrderTime().substring(0, 10).replace("-", ""))
                            && !"YS".equals(order.getOrderType())
                    ) {
                        System.err.println(order.getOrderTime().substring(0, 10).replace("-", ""));
                        System.err.println(now);
                        orderMapper.UpOrderStateById(order.getId(), "-1", token,null);
                        order.setState("-1");

                    }

                    if (now.equals(order.getOrderTime().substring(0, 10).replace("-", ""))
                        ){
                        dfk += 1;
                    }

                    break;
                case "1":
                    dfh += 1;

                    break;
                case "2":
                    yfh += 1;
                    break;
                case "3":
                    dpj += 1;
                    break;
                case "4":
                    ypj += 1;
                    break;
            }
        }

        HashMap<String, Integer> data = new HashMap<>();

        data.put("dfk", dfk);
        data.put("dfh", dfh);
        data.put("yfh", yfh);
        data.put("dpj", dpj);
        data.put("ypj", ypj);
        data.put("refund", Rcount);

        return data;
    }

    public static void main(String[] args) {
        SimpleDateFormat sdfe = new SimpleDateFormat("yyyy/MM/dd" + " " + "HH:mm:ss");
        try {
            System.err.println(sdfe.parse("2021/01/15 00:00:00")) ;
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void UpOrderState(String code, String state, String date) {
        orderMapper.upOrderStateByCode(code, state, date);
    }

    //购物车付款
    @Override
    public PayData createOrderByBasket(String uid, String openid, String aid, String mid,
                                       String cid, String phone, String token,
                                       String comment, String emp, String discount, String isPlus) throws OrderExceptionApp {
        Mail mail = new Mail();
        Info info = GetInfo(token);

        BigDecimal RECOUNT = new BigDecimal(0); //总实付金额

        String orderid = getOrderIdByUUId();
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String now = sdf.format(date);

        List<Basket> baskets = basketMapper.thisVipSelectedData(uid, token);

        // 遍历并计算总价：
        int totalPrice = 0;
        int totalIntegral = 0;

        int rp;
        int Coupond;
        ArrayList<Goods> disList = new ArrayList<Goods>();
        try {
            //判断优惠券是否可用 是 返回金额 否 返回异常

            //计算总 原价
            for (Basket basket : baskets) {
                Goods goods = goodsMapper.getGoods(basket.getGid());

                System.err.println(Long.parseLong(goods.getPrice()));
                System.err.println(Long.valueOf(basket.getNum()));

                //判断plus会员
                if (!"Y".equals(isPlus)) {
                    goods.setPlusPrice(null);
                }

                //计算会员价
                if ("Y".equals(goods.getIsVipPrice())) {
                    goods.setVipPrice(String.valueOf(MathUtil.multiply(new BigDecimal(goods.getOriginal()), new BigDecimal(discount), 0)));
                }


                goods.setPrice(minPrice(goods.getPrice(), goods.getVipPrice(), goods.getPlusPrice()));

                totalPrice += Long.parseLong(goods.getPrice()) * Long.valueOf(basket.getNum());
                totalIntegral += Long.valueOf(goods.getIntegral());
                //判断库存
                determineTheInventory(info, basket.getCode(), Integer.parseInt(basket.getNum()));

                if (null != goods.getActivityId() && !"0".equals(goods.getActivityId())) {
                    goods.setActivitieitem(appActivityService.getActvityById(goods.getActivityId()));

                    for (int i = 0; i < Integer.parseInt(basket.getNum()); i++) {
                        if (null == goods.getActivitieitem() || !"N".equals(goods.getActivitieitem().getIsUse())) {
                            disList.add(goods);
                        }
                    }

                }
                basket.setGoods(goods);
            }

            if ("-1".equals(mid)) {//包邮
                mail.setPrice("0");
                mail.setName("包邮");
            } else if ("-2".equals(mid)) {//积分减免
                QuerryMailFee querryMailFee = new QuerryMailFee(info.getUrl(), info.getAccount(), info.getPassword());
                String row = null;
                try {
                    row = querryMailFee.getData(phone);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if ("null".equals(row) || null == row) {
                    throw new OrderExceptionApp("出现错误,抵扣运费null");
                } else {
                    totalIntegral += Integer.parseInt(row);
                    mail.setPrice("0");
                }
            } else {
                mail = mailService.GetMail(mid);
            }


            rp = goodsActivity(totalPrice, disList);

            //需要的积分不等于0 判断会员积分
            if (totalIntegral > 0) {
                GETUserByOpenid getUserByOpenid = new GETUserByOpenid(info.getUrl(), info.getAccount(), info.getPassword());
                int integral = Integer.parseInt(getUserByOpenid.getData(openid).getIntegral());
                if (totalIntegral > integral) {
                    throw new OrderExceptionApp("创建订单失败！积分不足！");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new OrderExceptionApp(e.getMessage());
        }
        Coupon coupon = calculateCoupon(info, cid, totalPrice);
        Coupond = Integer.parseInt(coupon.getMoney());
        //计算总成交价
        System.err.println(totalPrice);
        rp = ActualPayment(rp, 0, Coupond);
        System.err.println("rp = " + rp);
        //计算总折扣

        BigDecimal bigDecimal = CalculateDiscount(rp, totalPrice);

        // 创建订单Order对象
        Order order = new Order();
        // 向Order对象封装uid
        order.setUid(uid);
        // 根据aid查询地址数据：addressService.getByAid(aid)
        Address address = addressService.getAddressById(aid);
        // 判断查询结果，如果为null，抛出异常
        if (address == null) {
            throw new OrderExceptionApp("创建订单失败！收货地址数据不存在！");
        }
        //零售单数据
        ArrayList<ArrayList> RETAIL = new ArrayList();
        /*RETAIL.put("Price",totalPrice);*/
        for (Basket basket : baskets) {
            //*********************************
            //零售单明细
            // for (int i = 0; i < Integer.parseInt(basket.getNum()); i++) {
            ArrayList list = new ArrayList();
            BigDecimal bigDecimal1 = CalculateUnit(Integer.parseInt(basket.getGoods().getPrice()) * Integer.parseInt(basket.getNum()), bigDecimal);
            RECOUNT = MathUtil.add(RECOUNT, bigDecimal1, 2);//加入总价
            list.add(basket.getCode());
            list.add(basket.getNum());
            list.add(bigDecimal1.toString());
            RETAIL.add(list);
            //  }
        }
        String orderType = "Z";
        //积分调整接口 积分大于0执行

        if (totalIntegral > 0) {
            CreateIntegral createIntegral = new CreateIntegral(info.getUrl(), info.getAccount(), info.getPassword());

            try {

                order.setIntegralCode(createIntegral.getData(phone, Long.toString(totalIntegral)));

            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.getMessage());
                order.setIntegralMessage(e.getMessage());
                throw new OrderExceptionApp("积分调整单错误" + e.getMessage());
            }
        }

        CreateYCRETAIL createYCRETAIL = new CreateYCRETAIL(info.getUrl(), info.getAccount(), info.getPassword());
        FindStoreData findStoreData = new FindStoreData(info.getUrl(), info.getAccount(), info.getPassword());

        try {//orderType  Z:正常订单,S:秒杀订单,P:拼团订单,K:砍价订单,Y:预售订单,
            //计算距离
            ArrayList<Store> stores = findStoreData.getData();

            CalculatStoreSpaceDistance(Double.parseDouble(address.getLongitude()), Double.parseDouble(address.getLatitude()), stores);
            String row = createYCRETAIL
                    .getData(orderType, RETAIL, RECOUNT.toString(), phone, orderid, mail, address, coupon, stores, comment, emp);
            order.setRetailCode(row);
        } catch (Exception e) {
            logger.error(e.getMessage());
            order.setRetailMessage(e.getMessage());
            throw new OrderExceptionApp("零售单错误" + e.getMessage());
        }

        // 向Order对象封装receiver,phone,address
        order.setReceiver(address.getReceiver());
        order.setPhone(address.getPhone());
        order.setAddress(address.getAddress());
        // 向Order对象封装state值为0
        order.setState("0");
        // 向Order对象封装orderTime为now
        //封装订单号
        order.setOrderId(orderid);
        order.setOrderTime(now);
        // 向Order对象封装total_price
        order.setTotalPrice(RECOUNT.toString().replace(".00", ""));
        order.setTotalIntegral(Long.toString(totalIntegral));
        // 向Order对象封装4项日志
        order.setCreatedUser(phone);
        order.setCreatedTime(now);
        order.setModifiedUser(phone);
        order.setModifiedTime(now);
        // 执行插入订单数据：insertOrder(order);
        order.setToken(token);
        order.setAccount(token);
        order.setMailFee(mail.getPrice());
        insertOrder(order);
        // 遍历查询结果
        for (Basket basket : baskets) {
            // 创建OrderItem对象
            OrderItem item = new OrderItem();
            // 向OrderItem对象中封装商品相关的5个数据
            item.setGoodsId(basket.getGid());
            item.settName(basket.getType());
            item.setCode(basket.getCode());
            item.setGoodsTitle(basket.getGoods().getName());
            item.setGoodsImage(basket.getGoods().getImg());
            item.setGoodsPrice(CalculateUnit(Integer.parseInt(basket.getGoods().getPrice()), bigDecimal).toString());
            System.err.println(item.getGoodsPrice());
            item.setGoodsIntegral(basket.getGoods().getIntegral());
            item.setGoodsNum(basket.getNum());

            item.setOid(order.getId());
            // 向OrderItem对象中封装日志
            item.setCreatedUser(phone);
            item.setCreatedTime(now);
            item.setModifiedUser(phone);
            item.setModifiedTime(now);
            //执行插入订单商品数据：insertOrderItem(orderItem);
            insertOrderItem(item);
        }
        if (null != cid) {
            UseCoupon(cid, info);//核销优惠券
        }

        // 删除购物车对应数据
        StringBuffer title = new StringBuffer();
        for (Basket basket : baskets) {
            basketMapper.delData(basket.getId());
            title.append(basket.getGoods().getName()).append("*").append(basket.getNum()).append(";");
        }

        PayData data = new PayData();//test
        RECOUNT = MathUtil.add(RECOUNT, BigDecimal.valueOf(Integer.parseInt(mail.getPrice())), 0);//test
        if (RECOUNT.doubleValue() > 0) {
            try {
                String notify_url = "https://lfwd.cloudsmicro.com/shop/pay/result";
                data = payWechatService.createUnified(notify_url, openid, token, order.getOrderId(), RECOUNT.toString(), String.valueOf(title));
                //返回
                data.setOrderId(order.getId());
            } catch (Exception e) {
                e.printStackTrace();
            }
            data.setType("price");
        } else {
            data.setOrderId(order.getId());
            integralPay(info, order, data);
        }

        return data;

    }

    private String minPrice(String value1, String value2, String value3) {

        int a = Integer.parseInt(value1 == null ? "2147483647" : value1);
        int b = Integer.parseInt(value2 == null ? "2147483647" : value2);
        int c = Integer.parseInt(value3 == null ? "2147483647" : value3);
        int n = a < b ? a : b; //找出a和b最小值。
        int m = n < c ? n : c;//用n和c比较。
        return String.valueOf(m);
    }

    private void UseCoupon(String cid, Info info) {
        Integer row = appCouponMapper.useCoupon(cid);
        if (1 != row) {
            System.err.println("优惠券核销:" + cid);
        }
       /* if (cid != null && cid.length() > 0) {
            ModUseCouponBos modUseCouponBos = new ModUseCouponBos(info.getUrl(), info.getAccount(), info.getPassword());
            try {
                modUseCouponBos.getData(cid);
            } catch (Exception e) {
                e.printStackTrace();
                System.err.println("核销优惠券错误");
            }
        }*/
    }

    //纯积分付款
    private void integralPay(Info info, Order order, PayData data) {
        data.setType("integral");
        Submit submit = new Submit(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            if (null != order.getIntegralCode()) {
                String icode = submit.getData(order.getIntegralCode(), "WX_VIPINTEGRALADJ");//提交积分调整单
                order.setIntegralCode(icode);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            order.setIntegralMessage(e.getMessage());
            e.printStackTrace();
        }
        try {
            if (null != order.getRetailCode()) {
                String rcode = submit.getData(order.getRetailCode(), "YC_RETAIL");//提交零售单
                order.setRetailCode(rcode);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            order.setRetailMessage(e.getMessage());
            e.printStackTrace();
        }
        data.setOrderId(order.getId());
        UpERPData(order);
    }


    //立即付款
    @Override
    @Transactional
    public PayData createOrder(String uid, String openid, String aid,
                               String mid, String gid, String cid, String code, String type,
                               String phone, String token, String comment, String emp, String discount, String isPlus)
            throws OrderExceptionApp {
        System.err.println("mid=" + mid);
        Info info = GetInfo(token);
        Goods goods = goodsService.findGoodsById(gid, uid, discount, isPlus);

        //判断库存
        determineTheInventory(info, code, 1);
        Mail mail = new Mail();


        if ("-1".equals(mid)) {//包邮
            mail.setPrice("0");
            mail.setName("包邮");
        } else if ("-2".equals(mid)) {//积分减免
            QuerryMailFee querryMailFee = new QuerryMailFee(info.getUrl(), info.getAccount(), info.getPassword());
            String row = null;
            try {
                row = querryMailFee.getData(phone);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if ("null".equals(row) || null == row) {
                throw new OrderExceptionApp("出现错误,抵扣运费null");
            } else {

                goods.setIntegral(String.valueOf(Integer.parseInt(goods.getIntegral()) + Integer.parseInt(row)));
                mail.setPrice("0");
            }
        } else {
            mail = mailService.GetMail(mid);
        }
        System.err.println(goods.getIntegral());

        Date date = new Date();
        String orderid = getOrderIdByUUId();


        //计算满减价格
        List<Goods> goodsList = new ArrayList<>();
        if (null != goods.getActivityId() && !"0".equals(goods.getActivityId())) {
            goods.setActivitieitem(appActivityService.getActvityById(goods.getActivityId()));
            if (null == goods.getActivitieitem() || !"N".equals(goods.getActivitieitem().getIsUse())) {
                goodsList.add(goods);
            }
        }

        int rp = goodsActivity(Integer.parseInt(goods.getPrice()), goodsList);

        //优惠券金额
        int Coupond;
        Coupon coupon = calculateCoupon(info, cid, Integer.parseInt(goods.getPrice()));
        try {
            //判断优惠券是否可用 是 返回金额 否 返回异常
            //Coupond = Integer.parseInt(calculateCoupon(info, cid, Integer.parseInt(goods.getPrice())).getMoney());

            Coupond = Integer.parseInt(coupon.getMoney());

            //需要的积分不等于0 判断商品积分
            if (Integer.parseInt(goods.getIntegral()) > 0) {
                GETUserByOpenid getUserByOpenid = new GETUserByOpenid(info.getUrl(), info.getAccount(), info.getPassword());
                int integral = Integer.parseInt(getUserByOpenid.getData(openid).getIntegral());
                if (Integer.parseInt(goods.getIntegral()) > integral) {
                    throw new OrderExceptionApp("创建订单失败！积分不足！");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new OrderExceptionApp(e.getMessage());
        }
        // 创建当前时间对象

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String now = sdf.format(date);
        //创建订单Order对象
        Order order = new Order();
        order.setUid(uid);

        // 根据aid查询地址数据：addressService.getByAid(aid)
        Address address = addressService.getAddressById(aid);
        // 判断查询结果，如果为null，抛出异常
        if (address == null) {
            throw new OrderExceptionApp("创建订单失败！收货地址数据不存在！");
        }


        //计算价格
        rp = ActualPayment(rp, 0, Coupond);
        System.err.println(rp);

        //实际价格
        BigDecimal sjjg = BigDecimal.valueOf(rp);

        ArrayList<ArrayList> RETAIL = new ArrayList<>();
        //**********************************
        //零售单明细
        ArrayList list = new ArrayList();
        list.add(code);
        list.add(1);
        list.add(sjjg);
        RETAIL.add(list);
        String orderType = "Z";
        //积分调整接口商品积分大于0时执行

        if (Integer.parseInt(goods.getIntegral()) > 0) {

            CreateIntegral createIntegral = new CreateIntegral(info.getUrl(), info.getAccount(), info.getPassword());
            //HashMap<String, String> integralmap = null;
            try {
                //integralmap = createIntegral.getData(phone, good.getIntegral());
                //order.setIntegralCode(integralmap.get("code"));
                order.setIntegralCode(createIntegral.getData(phone, goods.getIntegral()));
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.getMessage());
                order.setIntegralMessage(e.getMessage());
                throw new OrderExceptionApp("积分调整单错误" + e.getMessage());
            }
        }

        //零售单
        //CreateRetall createRetall = new CreateRetall(info.getUrl(), info.getAccount(), info.getPassword());
        CreateYCRETAIL createYCRETAIL = new CreateYCRETAIL(info.getUrl(), info.getAccount(), info.getPassword());
        FindStoreData findStoreData = new FindStoreData(info.getUrl(), info.getAccount(), info.getPassword());

        try {//orderType  Z:正常订单,S:秒杀订单,P:拼团订单,K:砍价订单,Y:预售订单,
            //计算距离
            ArrayList<Store> stores = findStoreData.getData();

            CalculatStoreSpaceDistance(Double.parseDouble(address.getLongitude()), Double.parseDouble(address.getLatitude()), stores);
            String row = createYCRETAIL.getData(orderType, RETAIL, sjjg.toString(), phone, orderid, mail, address, coupon, stores, comment, emp);
            order.setRetailCode(row);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            order.setRetailMessage(e.getMessage());
            throw new OrderExceptionApp("零售单错误" + e.getMessage());
        }
        // 向Order对象封装receiver,phone,address
        order.setReceiver(address.getReceiver());
        order.setPhone(address.getPhone());
        order.setAddress(address.getAddress());
        // 向Order对象封装state值为0
        order.setState("0");
        order.setOrderTime(now);
        order.setTotalPrice(String.valueOf(sjjg));
        order.setTotalIntegral(goods.getIntegral());
        order.setCreatedUser(phone);
        order.setCreatedTime(now);
        order.setModifiedUser(phone);
        order.setModifiedTime(now);
        order.setToken(token);
        order.setAccount(token);
        //封装订单号
        order.setOrderId(orderid);
        order.setMailFee(mail.getPrice());
        // 执行插入订单数据
        insertOrder(order);

        OrderItem item = new OrderItem();
        // 向OrderItem对象中封装商品相关的5个数据
        item.setGoodsId(goods.getId());
        item.setGoodsTitle(goods.getName());
        item.setGoodsImage(goods.getImg());
        item.settName(type);
        item.setCode(code);
        item.setGoodsPrice(sjjg.toString());
        item.setGoodsIntegral(goods.getIntegral());
        item.setGoodsNum("1");
        // 向OrderItem对象中封装oid：order.getOid()
        item.setOid(order.getId());
        // 向OrderItem对象中封装日志
        item.setCreatedUser(phone);
        item.setCreatedTime(now);
        item.setModifiedUser(phone);
        item.setModifiedTime(now);
        // 执行插入订单商品数据
        insertOrderItem(item);
        sjjg = MathUtil.add(sjjg, BigDecimal.valueOf(Integer.parseInt(mail.getPrice())), 0);
        //生成支付
        if (null != cid) {
            UseCoupon(cid, info);//核销优惠券
        }

        PayData data = new PayData();
        System.err.println(sjjg);
        if (sjjg.doubleValue() > 0) {
            try {
                String notify_url = "https://lfwd.cloudsmicro.com/shop/pay/result";
                data = payWechatService.createUnified(notify_url, openid, token, order.getOrderId(), sjjg.toString(), goods.getName());
                data.setOrderId(order.getId());

            } catch (Exception e) {
                e.printStackTrace();
                throw new OrderExceptionApp(e.getMessage());
            }
            data.setType("price");
        } else {
            //纯积分支付
            integralPay(info, order, data);
        }
        return data;
    }

    @Override
    public PayData integralOrderBirthdayZT(String uid, String openid, String phoneZT, String nameZT, String gid, String code, String store, String distance, String dateZT, String type, String phone, String token, String emp, String comment) {
        Info info = GetInfo(token);
        Goods goods = goodsService.findGoodsInfoById(gid);

        String orderid = getOrderIdByUUId();

        try {

            //需要的积分不等于0 判断商品积分
            if (Integer.parseInt(goods.getActivityIntegral()) > 0) {
                GETUserByOpenid getUserByOpenid = new GETUserByOpenid(info.getUrl(), info.getAccount(), info.getPassword());
                int integral = Integer.parseInt(getUserByOpenid.getData(openid).getIntegral());
                if (Integer.parseInt(goods.getActivityIntegral()) > integral) {
                    throw new OrderExceptionApp("创建订单失败！积分不足！");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new OrderExceptionApp(e.getMessage());
        }
        // 创建当前时间对象
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String now = sdf.format(new Date());
        //创建订单Order对象
        Order order = new Order();
        order.setUid(uid);

        //零售单明细
        ArrayList<ArrayList> RETAIL = new ArrayList<>();
        ArrayList list = new ArrayList();
        list.add(code);
        list.add(1);
        list.add(goods.getPrice());
        RETAIL.add(list);
        //积分调整接口商品积分大于0时执行
        if (Integer.parseInt(goods.getActivityIntegral()) > 0) {
            CreateIntegral createIntegral = new CreateIntegral(info.getUrl(), info.getAccount(), info.getPassword());
            try {
                order.setIntegralCode(createIntegral.getData(phone, goods.getActivityIntegral()));
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.getMessage());
                order.setIntegralMessage(e.getMessage());
                throw new OrderExceptionApp("积分调整单错误" + e.getMessage());
            }
        }

        CreateYCRETAIL_ZT createYCRETAIL_ZT = new CreateYCRETAIL_ZT(info.getUrl(), info.getAccount(), info.getPassword());

        Coupon coupon = new Coupon();
        coupon.setMoney("0");
        int self = new Random().nextInt(9000000) + 1000000;
        try {//orderType  Z:正常订单,S:秒杀订单,P:拼团订单,K:砍价订单,Y:预售订单,

            String row = createYCRETAIL_ZT.getData("J", RETAIL, store, distance, phoneZT, nameZT, goods.getPrice(), phone, orderid, coupon, self + "", dateZT, emp, comment);
            order.setRetailCode(row);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            order.setRetailMessage(e.getMessage());
            throw new OrderExceptionApp("零售单错误" + e.getMessage());
        }
        // 向Order对象封装receiver,phone,address
        order.setReceiver(nameZT);
        order.setPhone(phone);
        order.setAddress("会员自提:" + store);
        // 向Order对象封装state值为0
        order.setState("0");
        order.setOrderTime(now);
        order.setTotalPrice(goods.getPrice());
        order.setTotalIntegral(goods.getActivityIntegral());
        order.setCreatedUser(phone);
        order.setCreatedTime(now);
        order.setModifiedUser(phone);
        order.setModifiedTime(now);
        order.setToken(token);
        order.setAccount(token);
        order.setSelf(String.valueOf(self));
        //封装订单号
        order.setOrderId(orderid);
        order.setMailFee("0");
        // 执行插入订单数据
        insertOrder(order);

        OrderItem item = new OrderItem();
        // 向OrderItem对象中封装商品相关的5个数据
        item.setGoodsId(goods.getId());
        item.setGoodsTitle(goods.getName());
        item.setGoodsImage(goods.getImg());
        item.settName(type);
        item.setCode(code);
        item.setGoodsPrice(goods.getPrice());
        item.setGoodsIntegral(goods.getActivityIntegral());
        item.setGoodsNum("1");
        // 向OrderItem对象中封装oid：order.getOid()
        item.setOid(order.getId());
        // 向OrderItem对象中封装日志
        item.setCreatedUser(phone);
        item.setCreatedTime(now);
        item.setModifiedUser(phone);
        item.setModifiedTime(now);
        // 执行插入订单商品数据
        insertOrderItem(item);

        //生成支付

        PayData data = new PayData();
        System.err.println(goods.getPrice());
        if (Integer.parseInt(goods.getPrice()) > 0) {
            try {
                String notify_url = "https://lfwd.cloudsmicro.com/shop/pay/result";
                data = payWechatService.createUnified(notify_url, openid, token, order.getOrderId(), goods.getPrice(), goods.getName());
                data.setOrderId(order.getId());

            } catch (Exception e) {
                e.printStackTrace();
                throw new OrderExceptionApp(e.getMessage());
            }
            data.setType("price");
        } else {
            //纯积分支付
            integralPay(info, order, data);
        }

        data.setSelf(String.valueOf(self));
        return data;
    }

    @Override
    public PayData integralBirthdayOrder(String uid, String openid, String aid, String mid, String gid, String code, String type, String phone, String token, String comment, String emp) {
        Info info = GetInfo(token);
        Goods goods = goodsService.findGoodsInfoById(gid);

        Mail mail = new Mail();

        if ("-1".equals(mid)) {//包邮
            mail.setPrice("0");
            mail.setName("包邮");
        } else {
            mail = mailService.GetMail(mid);
        }
        Date date = new Date();
        String orderid = getOrderIdByUUId();
        //计算满减价格

        try {

            //需要的积分不等于0 判断商品积分
            if (Integer.parseInt(goods.getActivityIntegral()) > 0) {
                GETUserByOpenid getUserByOpenid = new GETUserByOpenid(info.getUrl(), info.getAccount(), info.getPassword());
                int integral = Integer.parseInt(getUserByOpenid.getData(openid).getIntegral());
                if (Integer.parseInt(goods.getActivityIntegral()) > integral) {
                    throw new OrderExceptionApp("创建订单失败！积分不足！");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new OrderExceptionApp(e.getMessage());
        }
        // 创建当前时间对象
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String now = sdf.format(date);
        //创建订单Order对象
        Order order = new Order();
        order.setUid(uid);
        // 根据aid查询地址数据：addressService.getByAid(aid)
        Address address = addressService.getAddressById(aid);
        // 判断查询结果，如果为null，抛出异常
        if (address == null) {
            throw new OrderExceptionApp("创建订单失败！收货地址数据不存在！");
        }
        //计算价格

        ArrayList<ArrayList> RETAIL = new ArrayList<>();
        //**********************************
        //零售单明细
        ArrayList list = new ArrayList();
        list.add(code);
        list.add(1);
        list.add(goods.getPrice());
        RETAIL.add(list);
        //积分调整接口商品积分大于0时执行
        if (Integer.parseInt(goods.getActivityIntegral()) > 0) {
            CreateIntegral createIntegral = new CreateIntegral(info.getUrl(), info.getAccount(), info.getPassword());

            try {

                order.setIntegralCode(createIntegral.getData(phone, goods.getActivityIntegral()));
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.getMessage());
                order.setIntegralMessage(e.getMessage());
                throw new OrderExceptionApp("积分调整单错误" + e.getMessage());
            }
        }

        CreateYCRETAIL createYCRETAIL = new CreateYCRETAIL(info.getUrl(), info.getAccount(), info.getPassword());
        FindStoreData findStoreData = new FindStoreData(info.getUrl(), info.getAccount(), info.getPassword());

        try {//orderType  Z:正常订单,S:秒杀订单,P:拼团订单,K:砍价订单,Y:预售订单,
            //计算距离
            ArrayList<Store> stores = findStoreData.getData();

            CalculatStoreSpaceDistance(Double.parseDouble(address.getLongitude()), Double.parseDouble(address.getLatitude()), stores);
            String row = createYCRETAIL.getData("J", RETAIL, goods.getPrice(), phone, orderid, mail, address, null, stores, comment, emp);
            order.setRetailCode(row);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            order.setRetailMessage(e.getMessage());
            throw new OrderExceptionApp("零售单错误" + e.getMessage());
        }
        // 向Order对象封装receiver,phone,address
        order.setReceiver(address.getReceiver());
        order.setPhone(address.getPhone());
        order.setAddress(address.getAddress());
        // 向Order对象封装state值为0
        order.setState("0");
        order.setOrderTime(now);
        order.setTotalPrice(goods.getPrice());
        order.setTotalIntegral(goods.getActivityIntegral());
        order.setCreatedUser(phone);
        order.setCreatedTime(now);
        order.setModifiedUser(phone);
        order.setModifiedTime(now);
        order.setToken(token);
        order.setAccount(token);
        //封装订单号
        order.setOrderId(orderid);
        order.setMailFee(mail.getPrice());
        // 执行插入订单数据
        insertOrder(order);

        OrderItem item = new OrderItem();
        // 向OrderItem对象中封装商品相关的5个数据
        item.setGoodsId(goods.getId());
        item.setGoodsTitle(goods.getName());
        item.setGoodsImage(goods.getImg());
        item.settName(type);
        item.setCode(code);
        item.setGoodsPrice(goods.getPrice());
        item.setGoodsIntegral(goods.getActivityIntegral());
        item.setGoodsNum("1");
        // 向OrderItem对象中封装oid：order.getOid()
        item.setOid(order.getId());
        // 向OrderItem对象中封装日志
        item.setCreatedUser(phone);
        item.setCreatedTime(now);
        item.setModifiedUser(phone);
        item.setModifiedTime(now);
        // 执行插入订单商品数据
        insertOrderItem(item);

        BigDecimal sjjg = MathUtil.add(new BigDecimal(goods.getPrice()), BigDecimal.valueOf(Integer.parseInt(mail.getPrice())), 0);


        PayData data = new PayData();
        System.err.println(sjjg);
        if (sjjg.doubleValue() > 0) {
            try {
                String notify_url = "https://lfwd.cloudsmicro.com/shop/pay/result";
                data = payWechatService.createUnified(notify_url, openid, token, order.getOrderId(), sjjg.toString(), goods.getName());
                data.setOrderId(order.getId());

            } catch (Exception e) {
                e.printStackTrace();
                throw new OrderExceptionApp(e.getMessage());
            }
            data.setType("price");
        } else {
            //纯积分支付
            integralPay(info, order, data);
        }
        return data;
    }


    //砍价自提支付
    @Override
    @Transactional
    public PayData bargainCreateOrderZT(
            String uid, String openid, String phoneZT, String nameZT, String gid, String code,
            String store, String distance, String dateZT, String type, String phone, String token, String emp, String comment)
            throws OrderExceptionApp {

        System.err.println(uid + openid + dateZT + store +
                gid + code + type + phone + token);

        Info info = GetInfo(token);

        Date date = new Date();
        String orderid = getOrderIdByUUId();
        Goods goods = goodsService.findGoodsById(gid, uid, "1", "N");
        //判断库存
        determineTheInventory(info, code, 1);
        // 创建当前时间对象

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String now = sdf.format(date);
        //创建订单Order对象
        Order order = new Order();
        order.setUid(uid);

        ArrayList<ArrayList> RETAIL = new ArrayList<>();
        //**********************************
        //零售单明细
        ArrayList list = new ArrayList();
        list.add(code);
        list.add(1);
        list.add(0);
        RETAIL.add(list);

        CreateYCRETAIL_ZT createYCRETAIL_ZT = new CreateYCRETAIL_ZT(info.getUrl(), info.getAccount(), info.getPassword());

        Coupon coupon = new Coupon();
        coupon.setMoney("0");
        int self = new Random().nextInt(9000000) + 1000000;
        Submit submit = new Submit(info.getUrl(), info.getAccount(), info.getPassword());
        try {//orderType  Z:正常订单,S:秒杀订单,P:拼团订单,K:砍价订单,Y:预售订单,
            //计算距离

            String row = createYCRETAIL_ZT.getData("K", RETAIL, store, distance, phoneZT, nameZT, "0", phone, orderid, coupon, self + "", dateZT, emp, comment);
            order.setRetailCode(row);
            String rcode = submit.getData(order.getRetailCode(), "YC_RETAIL");//提交零售单
            order.setRetailCode(rcode);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            order.setRetailMessage(e.getMessage());
            throw new OrderExceptionApp("零售单错误" + e.getMessage());
        }
        // 向Order对象封装receiver,phone,address
        order.setReceiver(nameZT);
        order.setPhone(phone);
        order.setAddress("会员自提:" + store);
        // 向Order对象封装state值为0
        order.setState("1");
        order.setOrderTime(now);
        order.setTotalPrice(String.valueOf(0));
        order.setTotalIntegral(goods.getIntegral());
        order.setCreatedUser(phone);
        order.setCreatedTime(now);
        order.setModifiedUser(phone);
        order.setModifiedTime(now);
        order.setToken(token);
        order.setAccount(token);
        //封装订单号
        order.setOrderId(orderid);
        //order.setMailFee(mail.getPrice());
        order.setSelf(String.valueOf(self));
        // 执行插入订单数据
        insertOrder(order);

        OrderItem item = new OrderItem();
        // 向OrderItem对象中封装商品相关的5个数据
        item.setGoodsId(goods.getId());
        item.setGoodsTitle(goods.getName());
        item.setGoodsImage(goods.getImg());
        item.settName(type);
        item.setCode(code);
        item.setGoodsPrice("0");
        item.setGoodsIntegral(goods.getIntegral());
        item.setGoodsNum("1");
        // 向OrderItem对象中封装oid：order.getOid()
        item.setOid(order.getId());
        // 向OrderItem对象中封装日志
        item.setCreatedUser(phone);
        item.setCreatedTime(now);
        item.setModifiedUser(phone);
        item.setModifiedTime(now);
        // 执行插入订单商品数据
        insertOrderItem(item);

        PayData data = new PayData();

        data.setOrderId(order.getId());
        data.setSelf(String.valueOf(self));

        return data;
    }

    //砍价付款
    @Override
    @Transactional
    public PayData bargainCreateOrder(
            String uid, String openid, String aid, String gid, String code,
            int mailFee, String type, String phone, String token, String comment)
            throws OrderExceptionApp {
        System.err.println(uid + openid + aid +
                gid + code + type + phone + token);
        Info info = GetInfo(token);

        Date date = new Date();
        String orderid = getOrderIdByUUId();
        Goods goods = goodsService.findGoodsById(gid, uid, "1", "N");
        //判断库存
        determineTheInventory(info, code, 1);
        // 创建当前时间对象

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String now = sdf.format(date);
        //创建订单Order对象
        Order order = new Order();
        order.setUid(uid);

        // 根据aid查询地址数据：addressService.getByAid(aid)
        Address address = addressService.getAddressById(aid);
        // 判断查询结果，如果为null，抛出异常
        if (address == null) {
            throw new OrderExceptionApp("创建订单失败！收货地址数据不存在！");
        }


        ArrayList<ArrayList> RETAIL = new ArrayList<>();
        //**********************************
        //零售单明细
        ArrayList list = new ArrayList();
        list.add(code);
        list.add(1);
        list.add(0);
        RETAIL.add(list);

        CreateYCRETAIL createYCRETAIL = new CreateYCRETAIL(info.getUrl(), info.getAccount(), info.getPassword());
        FindStoreData findStoreData = new FindStoreData(info.getUrl(), info.getAccount(), info.getPassword());
        Mail mail = new Mail();
        mail.setPrice(String.valueOf(mailFee));
        Coupon coupon = new Coupon();
        coupon.setMoney("0");
        try {//orderType  Z:正常订单,S:秒杀订单,P:拼团订单,K:砍价订单,Y:预售订单,
            //计算距离
            ArrayList<Store> stores = findStoreData.getData();
            CalculatStoreSpaceDistance(Double.parseDouble(address.getLongitude()), Double.parseDouble(address.getLatitude()), stores);
            String row = createYCRETAIL.getData("K", RETAIL, String.valueOf(mailFee), phone, orderid, mail, address, coupon, stores, comment, null);
            order.setRetailCode(row);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            order.setRetailMessage(e.getMessage());
            throw new OrderExceptionApp("零售单错误" + e.getMessage());
        }
        // 向Order对象封装receiver,phone,address
        order.setReceiver(address.getReceiver());
        order.setPhone(address.getPhone());
        order.setAddress(address.getAddress());
        // 向Order对象封装state值为0
        order.setState("-1");
        order.setOrderTime(now);
        order.setTotalPrice(String.valueOf(0));
        order.setTotalIntegral(goods.getIntegral());
        order.setCreatedUser(phone);
        order.setCreatedTime(now);
        order.setModifiedUser(phone);
        order.setModifiedTime(now);
        order.setToken(token);
        order.setAccount(token);
        //封装订单号
        order.setOrderId(orderid);
        order.setMailFee(mail.getPrice());
        // 执行插入订单数据
        insertOrder(order);

        OrderItem item = new OrderItem();
        // 向OrderItem对象中封装商品相关的5个数据
        item.setGoodsId(goods.getId());
        item.setGoodsTitle(goods.getName());
        item.setGoodsImage(goods.getImg());
        item.settName(type);
        item.setCode(code);
        item.setGoodsPrice("0");
        item.setGoodsIntegral(goods.getIntegral());
        item.setGoodsNum("1");
        // 向OrderItem对象中封装oid：order.getOid()
        item.setOid(order.getId());
        // 向OrderItem对象中封装日志
        item.setCreatedUser(phone);
        item.setCreatedTime(now);
        item.setModifiedUser(phone);
        item.setModifiedTime(now);
        // 执行插入订单商品数据
        insertOrderItem(item);
        //生成支付

        PayData data = new PayData();

        if (mailFee > 0) {
            try {
                String notify_url = "https://lfwd.cloudsmicro.com/shop/pay/result";
                data = payWechatService.createUnified(notify_url, openid, token, order.getOrderId(), String.valueOf(mailFee), goods.getName());

            } catch (Exception e) {
                e.printStackTrace();
                throw new OrderExceptionApp(e.getMessage());
            }
            data.setType("price");
        }
        data.setOrderId(order.getId());
        return data;
    }

    //团购付款
    @Override
    public PayData groupCreateOrder(String uid, String openid, String aid, String newPrice,
                                    String mid, String gid, String cid, String code, String type,
                                    String phone, String token, String comment, String emp)
            throws OrderExceptionApp {

        Mail mail = new Mail();
        if ("-1".equals(mid)) {//包邮
            mail.setPrice("0");
            mail.setName("包邮");
        } else {
            mail = mailService.GetMail(mid);
        }
        Info info = GetInfo(token);
        //判断库存
        determineTheInventory(info, code, 1);
        Date date = new Date();
        String orderid = getOrderIdByUUId();

        Goods goods = goodsService.findGoodsById(gid, uid, "1", "N");

        //优惠券金额
        int Coupond;
        Coupon coupon = calculateCoupon(info, cid, Integer.parseInt(newPrice));
        try {
            //判断优惠券是否可用 是 返回金额 否 返回异常
            //Coupond = Integer.parseInt(calculateCoupon(info, cid, Integer.parseInt(goods.getPrice())).getMoney());

            Coupond = Integer.parseInt(coupon.getMoney());

            //需要的积分不等于0 判断会员积分
            if (Integer.parseInt(goods.getIntegral()) > 0) {
                GETUserByOpenid getUserByOpenid = new GETUserByOpenid(info.getUrl(), info.getAccount(), info.getPassword());
                int integral = Integer.parseInt(getUserByOpenid.getData(openid).getIntegral());
                if (Integer.parseInt(goods.getIntegral()) > integral) {
                    throw new OrderExceptionApp("创建订单失败！积分不足！");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new OrderExceptionApp(e.getMessage());
        }
        // 创建当前时间对象

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String now = sdf.format(date);
        //创建订单Order对象
        Order order = new Order();
        order.setUid(uid);

        // 根据aid查询地址数据：addressService.getByAid(aid)
        Address address = addressService.getAddressById(aid);
        // 判断查询结果，如果为null，抛出异常
        if (address == null) {
            throw new OrderExceptionApp("创建订单失败！收货地址数据不存在！");
        }

        //计算价格
        int rp = ActualPayment(Integer.parseInt(newPrice), 0, Coupond);
        System.err.println(rp);
        //总折扣

        //实际价格
        BigDecimal sjjg = BigDecimal.valueOf(rp);

        ArrayList<ArrayList> RETAIL = new ArrayList<>();
        //**********************************
        //零售单明细
        ArrayList list = new ArrayList();
        list.add(code);
        list.add(1);
        list.add(sjjg);
        RETAIL.add(list);

        //积分调整接口商品积分大于0时执行
        if (Integer.parseInt(goods.getIntegral()) > 0) {
            CreateIntegral createIntegral = new CreateIntegral(info.getUrl(), info.getAccount(), info.getPassword());
            //HashMap<String, String> integralmap = null;
            try {
                //integralmap = createIntegral.getData(phone, good.getIntegral());
                //order.setIntegralCode(integralmap.get("code"));
                order.setIntegralCode(createIntegral.getData(phone, goods.getIntegral()));
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.getMessage());
                order.setIntegralMessage(e.getMessage());
                throw new OrderExceptionApp("积分调整单错误" + e.getMessage());
            }
        }

        //零售单
        //CreateRetall createRetall = new CreateRetall(info.getUrl(), info.getAccount(), info.getPassword());
        CreateYCRETAIL createYCRETAIL = new CreateYCRETAIL(info.getUrl(), info.getAccount(), info.getPassword());
        FindStoreData findStoreData = new FindStoreData(info.getUrl(), info.getAccount(), info.getPassword());

        try {//orderType  Z:正常订单,S:秒杀订单,P:拼团订单,K:砍价订单,Y:预售订单,
            //计算距离
            ArrayList<Store> stores = findStoreData.getData();

            CalculatStoreSpaceDistance(Double.parseDouble(address.getLongitude()), Double.parseDouble(address.getLatitude()), stores);
            String row = createYCRETAIL.getData("P", RETAIL, sjjg.toString(), phone, orderid, mail, address, coupon, stores, comment, emp);
            order.setRetailCode(row);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            order.setRetailMessage(e.getMessage());
            throw new OrderExceptionApp("零售单错误" + e.getMessage());
        }
        // 向Order对象封装receiver,phone,address
        order.setReceiver(address.getReceiver());
        order.setPhone(address.getPhone());
        order.setAddress(address.getAddress());
        // 向Order对象封装state值为0
        order.setState("-1");
        order.setOrderTime(now);
        order.setTotalPrice(String.valueOf(sjjg));
        order.setTotalIntegral(goods.getIntegral());
        order.setCreatedUser(phone);
        order.setCreatedTime(now);
        order.setModifiedUser(phone);
        order.setModifiedTime(now);
        order.setToken(token);
        order.setAccount(token);
        //封装订单号
        order.setOrderId(orderid);
        order.setMailFee(mail.getPrice());
        // 执行插入订单数据
        insertOrder(order);

        OrderItem item = new OrderItem();
        // 向OrderItem对象中封装商品相关的5个数据
        item.setGoodsId(goods.getId());
        item.setGoodsTitle(goods.getName());
        item.setGoodsImage(goods.getImg());
        item.settName(type);
        item.setCode(code);
        item.setGoodsPrice(sjjg.toString());
        item.setGoodsIntegral(goods.getIntegral());
        item.setGoodsNum("1");
        // 向OrderItem对象中封装oid：order.getOid()
        item.setOid(order.getId());
        // 向OrderItem对象中封装日志
        item.setCreatedUser(phone);
        item.setCreatedTime(now);
        item.setModifiedUser(phone);
        item.setModifiedTime(now);
        // 执行插入订单商品数据
        insertOrderItem(item);
        sjjg = MathUtil.add(sjjg, BigDecimal.valueOf(Integer.parseInt(mail.getPrice())), 0);
        //生成支付
        if (null != cid) {
            UseCoupon(cid, info);//核销优惠券
        }
        PayData data = new PayData();
        System.err.println(sjjg);
        data.setOrderId(order.getId());
        if (sjjg.doubleValue() > 0) {
            try {
                String notify_url = "https://lfwd.cloudsmicro.com/shop/pay/result";
                data = payWechatService.createUnified(notify_url, openid, token, order.getOrderId(), sjjg.toString(), goods.getName());
                data.setOrderId(order.getId());
            } catch (Exception e) {
                e.printStackTrace();
                throw new OrderExceptionApp(e.getMessage());
            }
            data.setType("price");
        } else {
            //纯积分支付
            integralPay(info, order, data);
            data.setOrderId(order.getId());
        }
        return data;
    }

    /**
     * 判断库存
     *
     * @param info
     * @param code
     * @param num
     * @throws OrderExceptionApp
     */
    private void determineTheInventory(Info info, String code, int num) throws OrderExceptionApp {
        QueryStorage queryStorage = new QueryStorage(info.getUrl(), info.getAccount(), info.getPassword());

        int count = 0;

        try {
            count = queryStorage.getData(code);
        } catch (Exception e) {
            System.err.println(e.getMessage());
            throw new OrderExceptionApp("创建订单失败！库存数量不足！");
        }
        if (num > count) {
            throw new OrderExceptionApp("创建订单失败！库存数量不足！");
        }

    }


    /**
     * 计算活动价格
     *
     * @param totalPrice
     * @param goodsList
     * @return
     */
    private int goodsActivity(int totalPrice, List<Goods> goodsList) {
        System.err.println("总价=" + totalPrice);

        Set<Activity> activitySet = new HashSet<Activity>();
        for (Goods goods : goodsList) {
            if (null != goods.getActivitieitem()) {
                activitySet.add(goods.getActivitieitem());
            }

        }
        for (Activity activity : activitySet) {
            int price = 0;
            int num = 0;
            boolean discount = false;
            BigDecimal multiply;
            for (Goods goods : goodsList) {
                if (activity.getId().equals(goods.getActivityId())) {
                    price += Integer.parseInt(goods.getPrice());
                    num += 1;
                }
                //判断是否满金额/数量
                if ("1".equals(activity.getType()) && price >= Integer.parseInt(activity.getValue1())) {
                    //满足金额 总价减优惠金额 停止循环 防止二次计算同一优惠
                    totalPrice -= Integer.parseInt(activity.getValue2());
                    price = 0;//每满x元减x元

                }
                if ("2".equals(activity.getType()) && num >= Integer.parseInt(activity.getValue1())) {

                    discount = true;//满x件 全部同活动商品x折

                }
            }
            if (discount) {
                BigDecimal totalPriceD = new BigDecimal(price);
                multiply = MathUtil.multiply(
                        MathUtil.divide(totalPriceD, new BigDecimal(10), 2),
                        new BigDecimal(activity.getValue2()), 0);
                totalPrice = totalPrice - (price - multiply.intValue());
            }
        }
        return totalPrice;
    }

    /**
     * 购物券
     * 判断总原价是否满足优惠券最小金额
     *
     * @param info
     * @param cid
     * @param price
     * @return
     * @throws OrderExceptionApp
     */

    private Coupon calculateCoupon(Info info, String cid, int price) throws OrderExceptionApp {
        //FindCouponById findCouponById = new FindCouponById(info.getUrl(), info.getAccount(), info.getPassword());
        Coupon coupon = new Coupon();
        System.err.println("cid=" + cid);
        try {
            if (!"".equals(cid) && cid != null) {
                //接口获取优惠券
                coupon = appCouponMapper.findCouponById(cid);

                if (null != coupon && null != coupon.getOriginal() && Integer.parseInt(coupon.getOriginal()) > price) {
                    throw new OrderExceptionApp("购物券未满" + coupon.getOriginal() + "元不可用");
                }
                if (null != coupon && null != coupon.getMoney()) {
                    return coupon;
                }
            } else {
                coupon.setMoney("0");
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new OrderExceptionApp(e.getMessage());
        }
        return coupon;
    }

    /**
     * 实付款金额
     * p原付款金额 m邮费 i积分减免 u优惠券减免
     */
    private static int ActualPayment(int p, int i, int u) {
        p = p - u;
        p = p - i;
        if (p < 0) {
            p = 0;
        }
        return p;
    }

    /**
     * 插入订单数据
     *
     * @param order 订单数据
     */
    private void insertOrder(Order order) throws OrderExceptionApp {
        Integer rows = orderMapper.insertOrder(order);
        if (rows != 1) {
            throw new OrderExceptionApp("创建订单数据时出现未知错误！");
        }
    }

    /**
     * 插入订单商品数据
     */
    private void insertOrderItem(OrderItem orderItem) throws OrderExceptionApp {
        Integer rows = orderMapper.insertOrderItem(orderItem);
        if (rows != 1) {
            throw new OrderExceptionApp("创建订单商品数据时出现未知错误！");
        }
    }

    private Info GetInfo(String token) {
        return accountMapper.GetTokenData(token);
    }

    public static String getOrderIdByUUId() {
        int machineId = 1;//最大支持1-9个集群机器部署
        int hashCodeV = UUID.randomUUID().toString().hashCode();
        if (hashCodeV < 0) {//有可能是负数
            hashCodeV = -hashCodeV;
        }
        // 0 代表前面补充0
        // 4 代表长度为4
        //  d 代表参数为正数型
        return machineId + String.format("%015d", hashCodeV);
    }

    /**
     * 计算实际价格/原价
     *
     * @param original
     * @param price
     * @return
     */
    private static BigDecimal CalculateDiscount(int original, int price) {
        if (original == 0 && price == 0) {
            return new BigDecimal(0);
        }
        BigDecimal bigDecimaly = new BigDecimal(original);
        BigDecimal bigDecimalc = new BigDecimal(price);
        BigDecimal bigDecimal = MathUtil.divide(bigDecimaly, bigDecimalc, 32);
        System.err.println(bigDecimal.intValue());
        return bigDecimal;
    }

    /**
     * 计算单品实际价格 保留两位小数
     *
     * @param original 单品原价
     * @param b        单品折扣
     * @return
     */

    private static BigDecimal CalculateUnit(int original, BigDecimal b) {
        if (original == 0 && b.doubleValue() <= 0) {
            return new BigDecimal(0);
        }
        BigDecimal bigDecimaly = new BigDecimal(original);
        bigDecimaly = MathUtil.multiply(bigDecimaly, b, 2);
        return bigDecimaly;
        //return MathUtil.divide(bigDecimaly, BigDecimal.valueOf(100), 2);
    }

    /**
     * 计算店仓距离
     *
     * @param longitude 经度
     * @param latitude  纬度
     * @param stores
     * @return
     */
    private static ArrayList<Store> CalculatStoreSpaceDistance(double longitude, double latitude, ArrayList<Store> stores) {

        for (Store store : stores) {
            double jl = AddressUtil.getDistance(latitude, longitude, store.getLatitude(), store.getLongitude());
            store.setDistance(jl);
        }
        return stores;
    }

    /**
     * 积分抵扣运费
     *
     * @param mid
     * @param mail
     * @param info
     * @param phone
     * @param integer
     * @return
     * @throws OrderExceptionApp
     */
    private Integer integerMail(String mid, Mail mail, Info info, String phone, Integer integer)
            throws OrderExceptionApp {
        if ("-1".equals(mid)) {//包邮
            mail.setPrice("0");
            mail.setName("包邮");
        } else if ("-2".equals(mid)) {//积分减免
            QuerryMailFee querryMailFee = new QuerryMailFee(info.getUrl(), info.getAccount(), info.getPassword());
            String row = null;
            try {
                row = querryMailFee.getData(phone);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if ("null".equals(row) || null == row) {
                throw new OrderExceptionApp("出现错误,抵扣运费null");
            } else {
                mail.setPrice("0");
                return integer += Integer.parseInt(row);
            }
        } else {
            mail = mailService.GetMail(mid);
        }
        return integer;
    }



}
